package org.ifilm.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ifilm.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * 
 * Project Contoller. All requests about projects will be here
 * @author Mustafa Genç
 *
 */
@Controller
@RequestMapping("/photo/**")
public class PhotoController {
	/**
	 *	file which is an application param
	 */
	@Value("${FILE_DIRECTORY}")
	private String fileDirectory;
	
	@Autowired
	FileService fileService;
	
	@RequestMapping(value = "/upload", method = {RequestMethod.POST, RequestMethod.GET})
	public ResponseEntity<Map<String, Object>> uploadPhoto(@RequestParam(value = "fileData") MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> responseBody = new HashMap<String, Object>();
		
		Long fileName = System.currentTimeMillis();
		String filePath = fileDirectory + "/" + fileName;
		
		//create parent directory, if it does not exist
		File pFile = new File(fileDirectory);
		pFile.mkdirs();
		
		try {
			File file = new File(filePath);
			file.createNewFile();
			
			FileOutputStream ost = new FileOutputStream(file);
			ost.write(multipartFile.getBytes());

			ost.flush();
			ost.close();
		} catch (IOException e) {
			//if exception occurs, then return null
			filePath = null;
			
			e.printStackTrace();
		}
		
		responseBody.put("fileName", fileName);
		
		return new ResponseEntity<Map<String, Object>>(responseBody, HttpStatus.OK);
	}
	
	@RequestMapping(value = "/getPhoto", method = {RequestMethod.GET})
	public void getPhoto(@RequestParam(value = "fileName") String fileName, HttpServletRequest request, HttpServletResponse response) {
		try {
			OutputStream stream = response.getOutputStream();
			
			fileService.deliverFile(fileDirectory + "/" + fileName, stream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}